1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*!
Logical primitives
*/
use super::*;

lazy_static! {
    /// The boolean type, with the default type
    pub static ref BOOL: TermId = TermId::from_term_direct(Term::Bool(Bool::default()));
    /// The constant `true`, with the default type
    pub static ref TRUE: TermId = TermId::from_term_direct(Term::Boolean(Boolean::from(true)));
    /// The constant `false`, with the default type
    pub static ref FALSE: TermId = TermId::from_term_direct(Term::Boolean(Boolean::from(false)));

    /// An annotation of the boolean type, with the default type
    pub static ref BOOL_ANNOT: Annotation = Annotation::from_ty(BOOL.clone()).expect("The type of booleans is always a type");
}

/// A Boolean term
#[derive(Debug, Clone)]
pub struct Boolean {
    /// The boolean underlying this term
    value: bool,
    /// The annotation of this term, if any
    annot: Annotation,
    /// The code of this term
    code: Code,
    /// The variable filter of this term
    filter: VarFilter,
    /// The pre-computed flags of this term
    flags: AtomicTyckFlags,
}

impl From<bool> for Boolean {
    fn from(value: bool) -> Self {
        Self::new_unchecked(value, None)
    }
}

impl Boolean {
    /// Create a new boolean term without any type-checking
    #[inline]
    pub fn new_unchecked(value: bool, annot: Option<Annotation>) -> Boolean {
        let annot = annot.unwrap_or_else(|| BOOL_ANNOT.clone());
        let code = Self::compute_code(value, &annot);
        let filter = Self::compute_filter(value, &annot);
        let flags = Self::compute_flags(value, &annot).into();
        Boolean {
            value,
            annot,
            code,
            filter,
            flags,
        }
    }

    /// Compute the code for a boolean term with a given optional annotation
    #[inline]
    pub fn compute_code(value: bool, annot: &Annotation) -> Code {
        let mut hasher = AHasher::new_with_keys(0x10, 0x01);
        value.hash(&mut hasher);
        let pre = hasher.finish();
        if *annot != *BOOL_ANNOT {
            annot.hash(&mut hasher);
        }
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter for a boolean term with a given optional annotation
    #[inline]
    pub fn compute_filter(_value: bool, annot: &Annotation) -> VarFilter {
        annot.get_filter()
    }

    /// Compute the flags for a boolean term with a given optional annotation
    #[inline]
    pub fn compute_flags(_value: bool, annot: &Annotation) -> TyckFlags {
        let is_trivial = *annot == *BOOL_ANNOT;
        TyckFlags::default()
            .with_flag(AnnotTyck, L4::with_true(is_trivial))
            .with_flag(LocalTyck, L4::with_true(is_trivial))
            .with_flag(GlobalTyck, L4::with_true(is_trivial))
    }

    /// Get this term as a boolean
    #[inline]
    pub fn as_bool(&self) -> bool {
        self.value
    }

    /// Get the annotation of this term
    #[inline]
    pub fn get_annot(&self) -> &Annotation {
        &self.annot
    }
}

/// An instance of the type of booleans
#[derive(Debug, Clone)]
pub struct Bool {
    /// The annotation of this term, if any
    annot: Option<Annotation>,
    /// The code of this term
    code: Code,
    /// The variable filter of this term
    filter: VarFilter,
    /// The pre-computed flags of this term
    flags: AtomicTyckFlags,
}

impl Default for Bool {
    #[inline]
    fn default() -> Self {
        Self::new_unchecked(None)
    }
}

impl Bool {
    /// Create a new boolean type without any type-checking
    #[inline]
    pub fn new_unchecked(annot: Option<Annotation>) -> Bool {
        let code = Self::compute_code(annot.as_ref());
        let filter = Self::compute_filter(annot.as_ref());
        let flags = Self::compute_flags(annot.as_ref()).into();
        Bool {
            annot,
            code,
            filter,
            flags,
        }
    }

    /// Compute the code for a universe term with a given optional annotation
    #[inline]
    pub fn compute_code(annot: Option<&Annotation>) -> Code {
        let mut hasher = AHasher::new_with_keys(0x445, 0x235);
        0x52.hash(&mut hasher);
        let pre = hasher.finish();
        if let Some(annot) = annot {
            annot.hash(&mut hasher)
        };
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter for a universe term with a given optional annotation
    #[inline]
    pub fn compute_filter(annot: Option<&Annotation>) -> VarFilter {
        annot.get_filter()
    }

    /// Compute the flags for a universe term with a given optional annotation
    #[inline]
    pub fn compute_flags(annot: Option<&Annotation>) -> TyckFlags {
        TyckFlags::default()
            .with_flag(AnnotTyck, L4::with_true(annot.is_none()))
            .with_flag(LocalTyck, L4::with_true(annot.is_none()))
            .with_flag(GlobalTyck, L4::with_true(annot.is_none()))
    }

    /// Get the annotation of this term
    #[inline]
    pub fn get_annot(&self) -> AnnotationRef {
        if let Some(annot) = &self.annot {
            annot.borrow_annot()
        } else {
            AnnotationRef::Universe(Universe::set())
        }
    }
}

impl Cons for Boolean {
    type Consed = Boolean;

    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        if let Some(annot) = self.annot.cons(ctx) {
            Some(Boolean {
                value: self.value,
                annot,
                code: self.code,
                filter: self.filter,
                flags: self.flags.clone(),
            })
        } else {
            None
        }
    }

    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Boolean {
    type Substituted = Boolean;

    fn subst_rec(
        &self,
        ctx: &mut (impl SubstCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error> {
        if let Some(annot) = self.annot.subst_rec(ctx)? {
            let code = Self::compute_code(self.value, &annot);
            let filter = Self::compute_filter(self.value, &annot);
            let flags = Self::compute_flags(self.value, &annot).into();
            Ok(Some(Boolean {
                value: self.value,
                annot,
                code,
                filter,
                flags,
            }))
        } else {
            Ok(None)
        }
    }

    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl HasDependencies for Boolean {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix) && (self.filter.exact() || self.annot.has_var_dep(ix, equiv))
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.annot.has_dep_below(ix, base)
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }
}

impl TermEq for Boolean {
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        Some(
            self.value == other.value
                && (!ctx.cmp_annot() || self.annot.eq_in(&other.annot, ctx)?),
        )
    }
}

impl Typecheck for Boolean {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        match &*self.annot.base() {
            Term::Bool(_b) => true,
            _ => false,
        }
    }

    #[inline]
    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.annot.tyck(ctx)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl Value for Boolean {
    type ValueConsed = Boolean;
    type ValueSubstituted = Boolean;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Boolean(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        Some(self.annot.borrow_annot())
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Boolean>, Error> {
        if let Some(ty) = ty {
            if let Some(annot) = self.get_annot().coerce_ty(&ty, ctx)? {
                self.annotate_unchecked(annot, ctx.cons_ctx())
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Boolean>, Error> {
        if let Some(true) = self.annot.ty().is_subtype(&annot.ty()) {
            Ok(None)
        } else {
            Ok(Some(Boolean::new_unchecked(self.value, Some(annot))))
        }
    }

    #[inline]
    fn is_subtype_in(
        &self,
        _other: &Term,
        _ctx: &mut (impl TermEqCtxMut + ?Sized),
    ) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(self.value, &*BOOL_ANNOT)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Boolean(other) => self.eq_in(other, ctx),
            other if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn into_id_direct(self) -> TermId {
        if self.annot == *BOOL_ANNOT {
            if self.value {
                TRUE.clone()
            } else {
                FALSE.clone()
            }
        } else {
            TermId::from_term_direct(Term::Boolean(self))
        }
    }

    #[inline]
    fn form(&self) -> Form {
        Form::BetaEta
    }
}

impl Cons for Bool {
    type Consed = Bool;

    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        if let Some(annot) = self.annot.cons(ctx) {
            Some(Bool {
                annot,
                code: self.code,
                filter: self.filter,
                flags: self.flags.clone(),
            })
        } else {
            None
        }
    }

    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Bool {
    type Substituted = Bool;

    fn subst_rec(
        &self,
        ctx: &mut (impl SubstCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error> {
        if let Some(annot) = self.annot.subst_rec(ctx)? {
            let code = Self::compute_code(annot.as_ref());
            let filter = Self::compute_filter(annot.as_ref());
            let flags = Self::compute_flags(annot.as_ref()).into();
            Ok(Some(Bool {
                annot,
                code,
                filter,
                flags,
            }))
        } else {
            Ok(None)
        }
    }

    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl HasDependencies for Bool {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix) && (self.filter.exact() || self.annot.has_var_dep(ix, equiv))
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.annot.has_dep_below(ix, base)
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }
}

impl TermEq for Bool {
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        Some(!ctx.cmp_annot() || self.annot.eq_in(&other.annot, ctx)?)
    }
}

impl Typecheck for Bool {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        if let Some(annot) = &self.annot {
            if let Some(universe) = annot.borrow_annot().as_universe() {
                Universe::set() <= universe
            } else {
                false
            }
        } else {
            true
        }
    }

    #[inline]
    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        if let Some(annot) = &self.annot {
            annot.tyck(ctx)
        } else {
            Some(true)
        }
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl Value for Bool {
    type ValueConsed = Bool;
    type ValueSubstituted = Bool;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Bool(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        Some(self.get_annot())
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Bool>, Error> {
        if let Some(ty) = ty {
            if let Some(annot) = self.get_annot().coerce_ty(&ty, ctx)? {
                self.annotate_unchecked(annot, ctx.cons_ctx())
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Bool>, Error> {
        if let Some(true) = self.get_annot().ty().is_subtype(&annot.ty()) {
            Ok(None)
        } else {
            Ok(Some(Bool::new_unchecked(Some(annot))))
        }
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, _ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Bool(_) => Some(true),
            _ if other.is_root() || other.is_local_ty() == Some(false) => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(None)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Bool(other) => self.eq_in(other, ctx),
            other if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn into_id_direct(self) -> TermId {
        if self.annot.is_none() {
            BOOL.clone()
        } else {
            TermId::from_term_direct(Term::Bool(self))
        }
    }

    #[inline]
    fn form(&self) -> Form {
        Form::BetaEta
    }
}

impl PartialEq for Boolean {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}

impl Eq for Boolean {}

impl Hash for Boolean {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value.hash(state);
        self.annot.hash(state)
    }
}

impl PartialEq for Bool {
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}

impl Eq for Bool {}

impl Hash for Bool {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.annot.hash(state);
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn basic_bool_properties() {
        let t = TRUE.clone();
        let f = FALSE.clone();
        let b = BOOL.clone();

        assert_ne!(t, f);
        assert_ne!(t, b);
        assert_ne!(f, b);
        assert_eq!(t, *TRUE);
        assert_eq!(f, *FALSE);
        assert_eq!(b, *BOOL);

        assert_ne!(t.code(), f.code());
        assert_ne!(t.code(), b.code());
        assert_ne!(f.code(), b.code());
        assert_eq!(t.code(), t.untyped_code());
        assert_eq!(f.code(), f.untyped_code());
        assert_eq!(b.code(), b.untyped_code());

        assert_eq!(t.form(), Form::BetaEta);
        assert_eq!(f.form(), Form::BetaEta);
        assert_eq!(b.form(), Form::BetaEta);

        assert_eq!(t.ty().as_deref(), Some(&*b));
        assert_eq!(t.ty().as_deref(), Some(&*b));
        assert_eq!(t.base().as_deref(), Some(&*b));
        assert_eq!(t.base().as_deref(), Some(&*b));
        assert_eq!(t.tyck(&mut Trivial::default()), Some(true));
        assert_eq!(f.tyck(&mut Trivial::default()), Some(true));
        assert_eq!(b.tyck(&mut Trivial::default()), Some(true));

        assert_eq!(b.is_local_ty(), Some(true));
        assert_eq!(t.is_local_ty(), Some(false));
        assert_eq!(f.is_local_ty(), Some(false));

        assert_eq!(t.cons(&mut ()), None);
        assert_eq!(f.cons(&mut ()), None);
        assert_eq!(b.cons(&mut ()), None);

        for x in [&f, &t, &b] {
            for y in [&f, &t, &b] {
                assert_eq!(x.eq_in(y, &mut Untyped), Some(x.as_ptr() == y.as_ptr()))
            }
        }
    }

    #[test]
    fn bool_id_cmp() {
        let mut ctx = StandardCtx::default();
        let t = TRUE.clone();
        let b = BOOL.clone();
        let id_b = Lambda::id_with(Some(b), ctx.cons_ctx())
            .unwrap()
            .into_id_with(ctx.cons_ctx());
        let id_t = App::new(id_b, t.clone(), ctx.cons_ctx()).into_id_with(ctx.cons_ctx());
        assert_eq!(id_t.eq_in(&t, &mut Untyped), None);
        assert_eq!(id_t.eq_in(&t, &mut Typed), None);
    }
}